package fun.stgoder.dev.listener.sdk;

import cn.hutool.core.thread.ThreadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HCNetSDKCache {
    private static Logger logger = LoggerFactory.getLogger(HCNetSDKCache.class);
    private static Map<String, HCNetSDKWrapper> sdkMap = new HashMap<>();

    private static Thread timer = new Thread(() -> {
        while (true) {
            sdkMap.forEach((ip, sdk) -> {
                if (sdk != null && !sdk.isInitSuccess()) {
                    try {
                        logger.info("reload sdk: " + ip);
                        sdk.login_V40();
                        sdk.setDVRMessageCallBack_V31();
                        sdk.setupAlarmChan_V41();
                        sdk.setInitSuccess(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            ThreadUtil.sleep(10, TimeUnit.MINUTES);
        }
    });

    static {
        timer.start();
    }

    public static HCNetSDKWrapper initAndPut(String ip, int port, String username, String password) {
        HCNetSDKWrapper sdk = new HCNetSDKWrapper(ip, port, username, password);
        try {
            sdk.init();
            sdk.login_V40();
            sdk.setDVRMessageCallBack_V31();
            sdk.setupAlarmChan_V41();
            sdk.setInitSuccess(true);
            logger.info("init sdk success: " + ip);
        } catch (Exception e) {
            e.printStackTrace();
        }

        sdkMap.put(ip, sdk);
        return sdk;
    }

    public static void cleanAndRemove(String ip) {
        try {
            HCNetSDKWrapper hcNetSDKWrapper = get(ip);
            if (hcNetSDKWrapper != null) {
                hcNetSDKWrapper.closeAlarmChan_V30();
                hcNetSDKWrapper.logout();
                hcNetSDKWrapper.cleanup();
            }
            sdkMap.remove(ip);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static HCNetSDKWrapper get(String ip) {
        return sdkMap.get(ip);
    }
}
